package com.example.controller

import com.example.service.FileService
import com.example.service.XmlService
import com.example.vo.DataBaseVo
import com.example.vo.Hospital
import java.text.SimpleDateFormat
import javax.servlet.http.HttpServletRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import groovy.sql.Sql
import com.example.constants.DataBaseConfig
import com.example.email.IEmailService
import com.example.email.SendEmailVo

/**
 * springboot配置支持跳转到jsp页面方法：https://www.cnblogs.com/yuxiaona/p/7677717.html
 * @author 张威
 *
 */
@Controller
class FileController {
	
	@Autowired
	private FileService fileService;
	@Autowired
	private XmlService xmlService;
	
	@Autowired
	private IEmailService emailService;
	
	static timerMap = new HashMap<String,Timer>();
	
	@GetMapping("/index")
	String index(HttpServletRequest request) {
		
		
		
		def xmlStr = fileService.readTextByName("hospital.xml")
		
		request.setAttribute("xmlStr", xmlStr.toString());
		
		
		List<Hospital> hospitalList = xmlService.readXmlHospitalList()
		
		request.setAttribute("list", hospitalList);
		
		return "/index";
	}
	
	@PostMapping("/updateHospitals")
	String updateHospitals(String hospitalXml,HttpServletRequest request) {
		
		
		fileService.saveText("hospital.xml",hospitalXml);
		
		List<Hospital> hospitalList = xmlService.readXmlHospitalList();
		
		// 24小时的毫秒设定
		final long timeInterval = 2 *  60 * 1000;//24 * 60 * 60 * 1000;
		
		Timer t = new Timer();
		if(timerMap.containsKey("Timers")) {
			Timer delTimer = timerMap.get("Timers");
			delTimer.cancel();
		}
		//设置定时器
		for(hos in hospitalList) {
			
			//当前日期
			SimpleDateFormat dsdf = new SimpleDateFormat("yyyy-MM-dd");
			Date dtime = dsdf.parse(dsdf.format(new Date()))
			//传过来的小时，分。秒
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			Date time = sdf.parse(hos.getTimerTime());
			
			//判断时间是否小于当前时间
			long f = dtime.getTime() +  time.getTime();
			long n = System.currentTimeMillis();
			if(f < n) {
				long newTime =  n +  timeInterval - ((n -f)%timeInterval);
				time = new Date(newTime);
				println time
			}
			
			def final Hospital hospital = hos
			t.scheduleAtFixedRate(new TimerTask() {
				@Override
				public void run() {
					println "执行定时器。。。。。"+hospital.getHospitalName();	
					try {
						handleByHospitalEmail(hospital)
					} catch (Exception e) {
						e.printStackTrace()
					}
				}
				
			}, time, timeInterval);
		
		}
		timerMap.put("Timers", t);
		
		return index(request);
	}
	
	/**
	 * 处理每家医院查询交易成功的订单并且发送email
	 */
	def void handleByHospitalEmail(Hospital hospital) {
		
		
		Map<String, DataBaseVo> dbmap = DataBaseConfig.instance.dbmap;
		
		DataBaseVo dbVo = dbmap.get(hospital.getDbServerName());
		
		def url = dbVo.getUrl()+hospital.getDbName();//'jdbc:postgresql://114.55.247.157:54201/ehospital2'
		def user = dbVo.getUser();//'testdev'
		def password = dbVo.getPassword();//'kYYfJ76c89alwgJr'
		def final  driver = 'org.postgresql.Driver';//我们目前只用到这个数据库
		if(url == null || user == null || password == null) {
			println "缺少数据库配置信息："+url+"--"+user+"---"+password
			return ;
		}
		def params = []
		params.add(hospital.getHospitalId());
		def List resultList;
		Sql.withInstance(url, user, password, driver) { sql ->
			/*sql.query("select o.trade_no,o.create_time,o.order_amount,o.pay_type,o.order_status,o.biz_id,o.data_src,p.real_name,p.id_card from new_order o left join patients p on  o.patient_id = p.patient_id and o.order_status  in ('2','4','41','42','7','9','11') where o.hospital_id = 'dysjyqzyyadmin' and  o.create_time > CURRENT_DATE") { resultSet ->
			  while (resultSet.next()) {
			    def trade_no = resultSet.getString(1)
			    def order_status = resultSet.getString('order_status')
				println trade_no
			  }
			}*/
			resultList = sql.rows("select o.trade_no,o.create_time,o.order_amount,o.pay_type,o.order_status,o.biz_id,o.data_src,"+
				" p.real_name,p.id_card,p.patient_card from new_order o left join patients p on  o.patient_id = p.patient_id and o.order_status "+
				" in ('2','4','41','42','7','9','11') where o.hospital_id = ? and  o.create_time > CURRENT_DATE -1 ",params)
		}
		
		println "订单条数："+resultList.size();
		
		StringBuilder sb = new StringBuilder();
		sb.append("您好，"+hospital.getHospitalId()+"--" + hospital.getDbServerName() + "测试环境数据库订单统计情况如下：<br/>");
		sb.append("<p style='color:red;'>统计订单状态为：2-支付成功未通知HIS,4-退款成功,41-退款（冲正）成功,42-撤销成功,7-支付成功且HIS失败,9-支付成功且HIS成功,11-订单关闭</p>");
		sb.append("<table border=1 style='text-align:center;' cellpadding='10' cellspacing='0'>");
		sb.append("<tr>");
			sb.append("<th>交易时间</th>");
			sb.append("<th>订单号</th>");
			sb.append("<th>订单金额</th>");
			sb.append("<th>支付方式</th>");
			sb.append("<th>支付来源</th>");
			sb.append("<th>订单状态</th>");
			sb.append("<th>业务bizid</th>");
			sb.append("<th>就诊人名称</th>");
			sb.append("<th>就诊人身份证</th>");
			sb.append("<th>就诊人卡号</th>");
		sb.append("</tr>");
		
		resultList.collect { 
			sb.append("<tr>");
				sb.append("<th>${it.create_time}</th>");
				sb.append("<th>${it.trade_no}</th>");
				sb.append("<th>${it.order_amount}</th>");
				sb.append("<th>${it.pay_type}</th>");
				sb.append("<th>${it.data_src}</th>");
				sb.append("<th>${it.order_status}</th>");
				sb.append("<th>${it.biz_id}</th>");
				sb.append("<th>${it.real_name}</th>");
				sb.append("<th>${it.id_card}</th>");
				sb.append("<th>${it.patient_card}</th>");
			sb.append("</tr>");
		}
		sb.append("</table>");
		println(sb.toString())
		SendEmailVo emailVo = new SendEmailVo();
		emailVo.setFromEmail("ehospital2@witontek.com");
		emailVo.setToEmail(hospital.getToEmail());
		emailVo.setSubject(hospital.getHospitalId()+"--" + hospital.getDbServerName() + "测试环境数据库订单统计情况"+new Date());
		emailVo.setContent(sb.toString());
		//emailService.sendMailHtml(emailVo);
		
	}
}
